package edu.nctu.csie.jichang.tw2cn.semantic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class Semantic {

	private static final Logger log = Logger.getLogger(Semantic.class.getName());
	private File semanticPath;
	private static Map<String, String> tw2cnMap;
	private static final String START_TW = "S";
	private static final String START_CN = "D";
	private static Semantic instance;
	
	private Semantic(){
		initialize();
	}

	public static Semantic getInstance() {
		if(instance == null){
			instance = new Semantic();
		}
		return instance;
	}
	
	private void initialize() {
		try {
			initPath();
			reload();
		} catch (Exception e) {
			new RuntimeException(e);
		}
	}
		
	private void reload() throws Exception {
		if(tw2cnMap!=null) tw2cnMap = null;
		tw2cnMap = new HashMap<String, String>();
		for (File f : semanticPath.listFiles()) {
			BufferedReader tReder = new BufferedReader(new InputStreamReader(new FileInputStream(f),"BIG5"));
			String tLine = null;
			while ((tLine = tReder.readLine())!=null) {
				if(tLine.length()>0){
					if(tLine.startsWith(START_TW)){
						String tCNLine = tReder.readLine();
						if(!tCNLine.startsWith(START_CN)){
							throw new Exception("File format error = " + f.getName() + " " + tLine);
						}
						tw2cnMap.put(tLine.substring(1).trim(), tCNLine.substring(1).trim());
					}
				}
			}
			tReder.close();
		}
	}

	private void initPath() {
		if(semanticPath == null) {
			String defPath = System.getProperty("semantic.dic.path");
			if(defPath == null){
				defPath = "semantic";
			}
			log.info("look up in semantic.dic.path="+defPath);
			semanticPath = new File(defPath);
			if(!semanticPath.exists()) {
				throw new RuntimeException("defalut dic path="+semanticPath+" not exist");
			}
		}
	}
	
	public String doExecute(String tFull,String pToken){
		if(pToken!=null && pToken.length() >0){
			pToken = pToken.trim();
			if(tw2cnMap.containsKey(pToken)){
				tFull.replaceAll(pToken, tw2cnMap.get(pToken));
			}
		}
		return tFull;
	}
	
	public String doExecute(String tFull){
		if(tFull!=null && tFull.length() >0){
			for (String tKey : tw2cnMap.keySet()) {
				tFull = tFull.replaceAll(tKey, tw2cnMap.get(tKey));
			}
		}
		return tFull;
	}
}
